<template>
    <div>
		<el-row :getter="24">
			<el-col :span="3">
				<el-select v-model="searchInfo.keyword" placeholder="请选择">
					<el-option label="用户名" value="username"></el-option>
					<el-option label="用户昵称" value="nick_name"></el-option>
					<el-option label="用户角色" value="authority_id"></el-option>
				</el-select>
			</el-col>
			<el-col :span="6" style="margin-left: 20px;">
				<el-input v-if="searchInfo.keyword !== 'authority_id'" placeholder="请输入内容" v-model="searchInfo.query" clearable @clear="getTableData"></el-input>
				<el-cascader 
						v-else
						style="line-height: 25px;"
				        v-model="searchInfo.query"
				        :options="authOptions"
				        :show-all-levels="false"
				        :props="{ checkStrictly: true,label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"
				        filterable
				></el-cascader>
			</el-col>
			<el-col :span="2"><el-button type="text" style="color: black;margin-left: 5px;font-weight: bolder;">状态</el-button></el-col>
			 <el-col :span="4">
				 <el-select v-model="searchInfo.user_state" placeholder="请选择用户状态">
					<el-option label="请选择" :value="2"></el-option>
					<el-option label="激活" :value="1"></el-option>
					<el-option label="未激活" :value="0"></el-option>
				</el-select>
			</el-col>
			<el-col :span="5" style="margin-left: 20px;">
				<el-button type="primary" @click="getTableData">查询</el-button>
			</el-col>
			<el-col :span="2">
				<el-button @click="showAddUserDialog" type="primary">新增用户</el-button>	
			</el-col>
		</el-row>
		 <el-row :gutter="10" style="margin-bottom: 8px;margin-top: 12px">
			 <el-col :span="1.5">
				 <el-button
						 type="danger"
						 icon="el-icon-delete"
						 size="mini"
						 :disabled="multiple"
						 @click="handleDelete"
				 >删除</el-button>
			 </el-col>
			 <el-col :span="1.5">
				 <el-button
						 type="danger"
						 icon="el-icon-delete"
						 size="mini"
						 @click="handleClean"
				 >清空</el-button>
			 </el-col>
			 <el-col :span="1.5">
				 <el-button
						 type="warning"
						 icon="el-icon-download"
						 size="mini"
						 :disabled="multiple"
						 @click="handleExportSelected"
				 >导出选中
				 </el-button>
			 </el-col>
			 <el-col :span="2">
				 <el-button
						 type="success"
						 icon="el-icon-download"
						 size="mini"
						 @click="handleExportAll"
				 >导出所有</el-button>
			 </el-col>
		 </el-row>
        <el-table :data="tableData" @sort-change="handleSortChange" border stripe :header-cell-style="table_header" :row-key="getRowKey" @selection-change="handleSelectionChange">
			<el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
			<el-table-column label="编号" width="50" align="center" prop="ID"></el-table-column>
			<el-table-column label="头像" min-width="80" align="center">
				<template slot-scope="scope">
					<a :style="{'textAlign':'center'}" :href="domain + scope.row.headerImg" target="_blank">
						<CustomPic :picSrc="scope.row.headerImg" :picTitle="scope.row.nickName" />
					</a>
				</template>
			</el-table-column>
            <el-table-column label="用户名" min-width="90" prop="userName" align="center"></el-table-column>
            <el-table-column label="昵称" min-width="90" prop="nickName" align="center"></el-table-column>
            <el-table-column label="性别" min-width="70" prop="gender" align="center">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.gender == 1">{{ scope.row.gender | formatGender }}</el-tag>
					<el-tag type="danger" v-else-if="scope.row.gender == 2">{{ scope.row.gender | formatGender }}</el-tag>
					<el-tag type="warning" v-else>{{ scope.row.gender | formatGender }}</el-tag>
				</template>
			</el-table-column>
            <el-table-column label="用户角色" min-width="100" align="center">
              <template slot-scope="scope">
                <el-tag type="success">{{scope.row.authority.authorityName}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width="80" prop="state" align="center">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
                </template>
            </el-table-column>
			<el-table-column label="创建日期" align="center" width="170" sortable="custom" prop="CreatedAt">
				 <template slot-scope="scope">
					 <span>{{ scope.row.CreatedAt | parseTime }}</span>
				 </template>
			 </el-table-column>
            <el-table-column label="操作" min-width="160" align="center">
                <template slot-scope="scope">
                    <el-tooltip
						class="item"
						effect="dark"
						content="编辑用户"
						:enterable="false"
						placement="top"
                    >
                        <el-button
								class="oper_button"
                                type="primary"
                                icon="el-icon-edit"
                                size="mini"
                                circle
                                @click="showEditUserDialog(scope.row)"
                        ></el-button>
                    </el-tooltip>
                    <el-tooltip
                            class="item"
                            effect="dark"
                            content="设置头像"
                            :enterable="false"
                            placement="top"
                    >
                        <el-button
								class="oper_button"
                                type="warning"
                                icon="el-icon-setting"
                                size="mini"
                                circle
                                @click="toggleShow(scope.row.ID)"
                        >
						</el-button>
                    </el-tooltip>
					<el-tooltip
					        class="item"
					        effect="dark"
					        content="删除用户"
					        :enterable="false"
					        placement="top"
					>
					    <el-button
								class="oper_button"
					            type="danger"
					            icon="el-icon-delete"
					            size="mini"
					            circle
					            @click="deleteUser(scope.row)"
					    ></el-button>
					</el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="page"
                :page-size="pageSize"
                :page-sizes="[10, 30, 50, 100]"
                :style="{float:'right',padding:'20px'}"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
				background
				prev-text="上一页"
				next-text="下一页"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <my-upload field="img"
        	 @crop-success="cropSuccess"
        	 @crop-upload-success="cropUploadSuccess"
        	 @crop-upload-fail="cropUploadFail"
        	 v-model="upload_show"
        	 method="PUT"
        	 :width="300"
        	 :height="300"
        	 :url="domain + '/user/uploadUserAvatar'"
        	 :params="params"
        	 :headers="headers"
        ></my-upload>
        <el-dialog :visible.sync="UserDialogVisible" custom-class="user-dialog" :before-close="closeUserDialog" :title="Dialog_title">
            <el-form :rules="rules" ref="userForm" :model="UserInfo">
                <el-form-item label="用户名" label-width="80px" prop="userName">
                    <el-input v-model="UserInfo.userName"></el-input>
                </el-form-item>
                <el-form-item label="别名" label-width="80px" prop="nickName">
                    <el-input v-model="UserInfo.nickName"></el-input>
                </el-form-item>
				<el-form-item label="性别" label-width="80px" prop="gender">
					  <el-radio v-model="UserInfo.gender" :label="1">男</el-radio>
					  <el-radio v-model="UserInfo.gender" :label="2">女</el-radio>
				</el-form-item>
				<el-form-item label="角色" label-width="80px" prop="authorityId">
					 <el-cascader
					         v-model="UserInfo.authorityId"
					         :options="authOptions"
					         :show-all-levels="false"
					         :props="{ checkStrictly: true,label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"
					         filterable
					 ></el-cascader>
				</el-form-item>
              <!--  <el-form-item label="头像" label-width="80px" prop="headerImg">
                    <div style="display:inline-block">
                        <img class="header-img-box" v-if="UserInfo.headerImg" :src="getImgUrl(UserInfo.headerImg)"/>
                        <el-button v-if="UserInfo.headerImg" type="primary" style="margin-left: 100px;" @click="toggleShow()">更换头像</el-button>
                        <el-button v-else type="primary" style="margin-left: 100px;" @click="toggleShow()">上传头像</el-button>
                    </div>
					  <my-upload field="img"
								 @crop-success="cropSuccess"
								 @crop-upload-success="cropUploadSuccess"
								 @crop-upload-fail="cropUploadFail"
								 v-model="upload_show"
								 method="POST"
								 :width="300"
								 :height="300"
								 :url="domain + '/user/uploadUserAvatar'"
								 :params="params"
								 :headers="headers"
					  ></my-upload>
                </el-form-item> -->
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeUserDialog">取 消</el-button>
                <el-button @click="AddOrUpdateUser" type="primary">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog
                title="分配角色"
                :visible.sync="setRoleDialogVisible"
                width="40%"
                center
                @close="setRoleDialogClosed"
        >
            <div class="allotRole">
                <p>当前用户： {{UserInfo.userName}}</p>
                <p>当前角色： {{UserInfo.authorityName}}</p>
                <p>
                    分配角色：
                  <el-cascader
                          v-model="selectRoleId"
                          :options="authOptions"
                          :show-all-levels="false"
                          :props="{ checkStrictly: true,label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"
                          filterable
                  ></el-cascader>
<!--                    <el-select-->
<!--                            v-model="selectRoleId"-->
<!--                            filterable-->
<!--                            allow-create-->
<!--                            default-first-option-->
<!--                            placeholder="请选择角色标签"-->
<!--                    >-->
<!--                        <el-option-->
<!--                                v-for="item in authOptions"-->
<!--                                :key="item.authorityId"-->
<!--                                :label="item.authorityName"-->
<!--                                :value="item.authorityId"-->
<!--                        ></el-option>-->
<!--                    </el-select>-->
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeAuthority">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成
    const path = process.env.VUE_APP_BASE_API;
    import {
        deleteUser,
        getUserList,
        getUserListByIds,
        register,
        setUserAuthority,
        setUserState,
        setUserInfo,
        batchDeleteUsers,
        cleanUsers
    } from "@/api/user";
    import {getAuthorityList} from "@/api/authority";
    import {formatUserJson} from "@/utils/index";
	import {getDict} from "@/utils/dictionary"
    import infoList from "@/mixins/infoList";
    import {mapGetters} from "vuex";
    import CustomPic from "@/components/customPic";
    import myUpload from 'vue-image-crop-upload';
    import 'babel-polyfill'

    export default {
        name: "Api",
        mixins: [infoList],
        components: {
          CustomPic,
          'my-upload': myUpload,
        },
        data() {
            return {
                listApi: getUserList,
                path: path,
                authOptions: [],
                selectRoleId: "",
                setRoleDialogVisible: false,
                UserDialogVisible: false,
                Dialog_title: "",
				Dialog_state: '',
                upload_show: false,
                UserInfo: {
                    userName: "",
					gender: 1,
                    // password: "",
                    nickName: "",
                    headerImg: "",
                    authorityId: "",
                    authorityName: "",
                },
                rules: {
                    userName: [
                        {required: true, message: "请输入用户名", trigger: "blur"},
                        {min: 5, message: "最低5位字符", trigger: "blur"}
                    ],
                    nickName: [
                        {required: true, message: "请输入用户昵称", trigger: "blur"}
                    ],
					gender: [
					    {required: true, message: "请选择用户性别", trigger: "blur"}
					],
                    authorityId: [
                        {required: true, message: "请选择用户角色", trigger: "blur"}
                    ]
                },
				params: {'name': 'avatar', 'user_id': ""},
				headers: {'x-token': "", 'x-user-id': ""},
				downloadLoading: false,
				// 选中数组
				ids: [],
				// 非多个禁用
				multiple: true,
				sexMap: {}
            };  
        },
        computed: {
            ...mapGetters("user", ["token", "userInfo"])
        },
        methods: {
			table_header(row, column, rowIndex, columnIndex){
				return 'background-color: #409EFF; color:white;font-size: 12px'
			},
			// 自定义排序
			handleSortChange({ column, prop, order }) {
			  this.searchInfo.sort_column = prop === 'CreatedAt' ? 'created_at' : prop;
			  this.searchInfo.order = order === 'ascending' ? 'asc' : 'desc';
			  // 使用构建好的排序参数，请求后端排序好的列表数据 tableData
			  this.getTableData();
			},
            setOptions(authData) {
                this.authOptions = [];
                this.setAuthorityOptions(authData, this.authOptions);
            },
            getImgUrl(img_url){
              if (img_url.slice(0, 4) === 'http'){
                return img_url
              }
              return this.domain + img_url
            },
            toggleShow(user_id) {
			  this.params.user_id = user_id;
              this.upload_show = !this.upload_show;
            },
            cropSuccess(imgDataUrl, field) {
				console.log('裁剪成功');
            },
            async cropUploadSuccess(data, field) {
              // this.UserInfo.headerImg = this.domain + data.data.img_path;
			  this.$message.success("上传成功");
              this.upload_show = false;
			  await this.getTableData()
            },
            cropUploadFail(status, field) {
              this.$message.error("上传失败");
            },
            // 监听用户状态改变事件
            async userStateChanged(UserInfo) {
                const res = await setUserState({"user_id": UserInfo.ID, "state": UserInfo.state});
                if (res.code === 0) {
                    this.$message.success("更新用户 " + UserInfo.userName + " 状态成功")
                } else {
                    this.$message.error("更新用户 " + UserInfo.userName + " 状态失败");
                }
            },
            setAuthorityOptions(AuthorityData, optionsData) {
                AuthorityData &&
                AuthorityData.map(item => {
                    if (item.children && item.children.length) {
                        const option = {
                            authorityId: item.authorityId,
                            authorityName: item.authorityName,
                            children: []
                        };
                        this.setAuthorityOptions(item.children, option.children);
                        optionsData.push(option);
                    } else {
                        const option = {
                            authorityId: item.authorityId,
                            authorityName: item.authorityName
                        };
                        optionsData.push(option);
                    }
                });
            },
            async deleteUser(row) {
				const confirmResult = await this.$confirm(
				                '此操作将永久删除该用户, 是否继续?',
				                '提示',
				                {
				                confirmButtonText: '确定',
				                cancelButtonText: '取消',
				                type: 'warning'
				                }
				            ).catch(err => err);
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消删除')
				}
				const res = await deleteUser({id: row.ID});
				if (res.code !== 0) {
					return this.$message.error('删除用户失败！')
				}
				await getTableData();
				this.$message.success('删除用户成功！');
            },
            closeUserDialog() {
                this.$refs.userForm.resetFields();
                this.UserDialogVisible = false;
            },
            handleAvatarSuccess(res) {
                this.UserInfo.headerImg = res.data.file.url;
            },
            showAddUserDialog() {
                this.UserInfo = {};
				this.Dialog_state = 'add';
				this.Dialog_title = '添加用户'
                this.UserDialogVisible = true;
            },
            showEditUserDialog(user) {
              this.UserInfo = JSON.parse(JSON.stringify(user));
			  this.Dialog_state = 'edit';
			  this.Dialog_title = '编辑用户'
              this.UserDialogVisible = true;
            },
            // 添加或更新用户
            AddOrUpdateUser() {
				var userForm = JSON.parse(JSON.stringify(this.UserInfo));
                if (this.Dialog_state === "add") {
                    this.$refs.userForm.validate(async valid => {
						if (valid) {
						    const res = await register(userForm);
						    if (res.code !== 0) {
								return this.$message.error("创建用户失败")
						    }
							this.closeUserDialog();
							this.$message({type: "success", message: "创建成功"});
							await this.getTableData();
						}
                    })
                }
				if (this.Dialog_state === 'edit') {
                    this.$refs.userForm.validate(async valid => {
                        if (!valid) return;
						const res = await setUserInfo(userForm);
                        if (res.code !== 0) {
                            return this.$message.error('更新用户信息失败！')
                        }
						this.closeUserDialog();
                        this.$message.success('更新用户信息成功！')
						await this.getTableData();
					})
                }
			},
            async changeAuthority() {
                const res = await setUserAuthority({
                    uuid: this.UserInfo.uuid,
                    authorityId: this.selectRoleId,
                });
                if (res.code === 0) {
                    this.$message({type: "success", message: "角色设置成功"});
                    this.setRoleDialogClosed();
                    this.getTableData();
                }else {
                  this.$message({type: "error", message: "角色设置失败"});
                }
            },
            // 展示分配角色的对话框
            async showSetRole (user) {
              this.UserInfo = user;
              this.selectRoleId = user.authorityId;
              this.UserInfo.authorityName = user.authority.authorityName;
              this.setRoleDialogVisible = true;
            },
            // 分配角色对话框关闭事件
            setRoleDialogClosed () {
              this.selectRoleId = '';
              this.setRoleDialogVisible = false
            },
			getRowKey(row){
				return row.ID;
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.ID);
				this.multiple = !selection.length
			},
		   /** 删除按钮操作 */
            handleDelete() {
               const Ids = this.ids;
               if (Ids.length < 1){
                   return this.$message.error('未选中删除的数据，至少选择一项')
               }
               this.$confirm('是否确认删除用户编号为"' + Ids + '"的数据项?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					const res = await batchDeleteUsers(Ids);
                    if (res.code !== 0){
                        return this.$message.error('删除失败', res.msg);
                    }
                    this.$message.success("删除成功");
                    this.getTableData();
				}).catch(function() {})
			},
			  /** 清空按钮操作 */
			handleClean() {
				this.$confirm('是否确认清空所有用户?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					this.$message.info('正在清空');
					const res = await cleanUsers({'clean': true});
					if (res.code !== 0){
						return this.$message.error('删除失败', res.msg);
					}
					this.$message.success("清空成功");
					this.getTableData();
				}).catch(function() {})
			},
			/** 导出按钮操作 */
			handleExportSelected() {
				const ids = this.ids;
				this.$confirm('是否确认导出选中的用户?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					this.downloadLoading = true;
					const res = await getUserListByIds({ids});
					if (res.code !== 0){
						return this.$message.error('导出失败', res.msg);
					}
					import('@/utils/Export2Excel').then(excel => {
						const tHeader = ['编号', '头像', '用户名', '昵称', '性别', '角色', '状态', '创建时间'];
						const filterVal = ['ID', 'headerImg', 'userName', 'nickName', 'gender', 'authority.authorityName', 'state', 'CreatedAt'];
						const data = formatUserJson(filterVal, res.data);
						excel.export_json_to_excel({
							header: tHeader,
							data,
							filename: '用户信息',
							autoWidth: true, // Optional
							bookType: 'xlsx' // Optional
						});
						this.$message.success('导出成功');
						this.downloadLoading = false
					});
				})
			},
			handleExportAll() {
				this.$confirm('是否确认导出所有用户数据?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					this.downloadLoading = true;
					const res = await getUserList({page: -1, pageSize: -1, user_state: 2});
					if (res.code !== 0){
						return this.$message.error('导出失败', res.msg);
					}
					import('@/utils/Export2Excel').then(excel => {
						const tHeader = ['编号', '头像', '用户名', '昵称', '性别', '角色', '状态', '创建时间'];
						const filterVal = ['ID', 'headerImg', 'userName', 'nickName', 'gender', 'authority.authorityName', 'state', 'CreatedAt'];
						const data = formatUserJson(filterVal, res.data);
						excel.export_json_to_excel({
							header: tHeader,
							data,
							filename: '用户信息',
							autoWidth: true, // Optional
							bookType: 'xlsx' // Optional
						});
						this.$message.success('导出成功');
						this.downloadLoading = false
					});
				})
			},
        },
      async created() {
        this.searchInfo.keyword = 'username';
        this.headers = {'x-token': this.token};
        // this.headers = {'x-token': this.token, 'x-user-id': this.userInfo.ID};
        this.getTableData();
        const res = await getAuthorityList({page: 1, pageSize: 999});
        this.setOptions(res.data.list);
        // getDict('sex').then(res1 => {
        // 	console.log(res1);
        // });
        // const res2 = await getDict('sex');
        // for(var i=0; i<res2.length; i++){
        // 	this.sexMap[res2[i].value] = res2[i].label
        // }
        // console.log(this.sexMap)
        // console.log(res2);
        },
    };
</script>
<style lang="scss">
    .user-dialog {
      .header-img-box {
          width: 200px;
          height: 200px;
          border: 1px dashed #ccc;
          border-radius: 20px;
          text-align: center;
          line-height: 200px;
          cursor: pointer;
      }

      .avatar-uploader .el-upload:hover {
          border-color: #409eff;
      }

      .avatar-uploader-icon {
          border: 1px dashed #d9d9d9 !important;
          border-radius: 6px;
          font-size: 28px;
          color: #8c939d;
          width: 178px;
          height: 178px;
          line-height: 178px;
          text-align: center;
      }

      .avatar {
          width: 178px;
          height: 178px;
          display: block;
      }
  }
    .allotRole{
      padding-left: 10% !important;
      line-height: 40px;
    }
	// .oper_button{
	// 	margin-left: 10px;
	// }
	.el-table__body-wrapper tr td .cell .el-button + .el-button{
		margin-left: 10px;
	}
	div.admin-box > div.el-row > div.el-col > div > div > input{
		font-weight: bold;
		text-align: center;
	}
	li.el-select-dropdown__item{
		text-align: center;
	}
	// div.admin-box > div.el-row > div.el-col.el-col-4 > div > div > input{
	// 	font-weight: bold;
	// 	text-align: center;
	// }
</style>